<template>
	<view class="my">
		<!-- 用户信息区域 -->
		<view class="user-info" v-if="isLogin">
			<view class="info-content" @tap="handleUserInfo">
				<image 
					class="avatar" 
					:src="userInfo.avatar ? ($baseUrl + userInfo.avatar) : '/static/avatar/default.png'" 
					mode="aspectFill"
				></image>
				<view class="info">
					<view class="name">{{ userInfo.username }}</view>
					<view class="phone">{{ formatPhone(userInfo.userPhone) }}</view>
				</view>
			</view>
			<view class="edit-icon" @tap="handleEditUserInfo">
				<image src="/static/icons/edit.png" mode="aspectFit"></image>
			</view>
		</view>
		<view class="user-info" v-else>
			<image class="avatar" src="/static/avatar/default.png" mode="aspectFill"></image>
			<button class="login-btn" @tap="handleLogin">
				<text>立即登录</text>
			</button>
		</view>

		<!-- 服务功能区域 -->
		<view class="service-section">
			<text class="section-title">服务功能</text>
			<view class="service-list">
				<!-- 我的订单 -->
				<view class="service-item" @tap="handleService('order')">
					<image class="icon" src="/static/tabbar/order-active.jpg" mode="aspectFit"></image>
					<text class="text">我的订单</text>
					<text class="arrow">></text>
				</view>

				<!-- 我的预约 -->
				<view class="service-item" @tap="handleService('booking')">
					<image class="icon" src="/static/tabbar/booking-active.jpg" mode="aspectFit"></image>
					<text class="text">我的预约</text>
					<text class="arrow">></text>
				</view>
				<!-- 常见问题-->
				<view class="service-item" @tap="handleService('room')">
					<image class="icon" src="/static/icons/question.png" mode="aspectFit"></image>
					<text class="text">常见问题</text>
					<text class="arrow">></text>
				</view>
				<!-- 联系客服 -->
				<view class="service-item" @tap="handleService('service')">
					<image class="icon" src="/static/icons/phone.png" mode="aspectFit"></image>
					<text class="text">联系客服</text>
					<text class="arrow">></text>
				</view>
			</view>
		</view>

		<!-- 编辑弹窗 -->
		<view class="edit-popup" v-if="showEditPopup">
			<view class="edit-content">
				<view class="title">修改头像和昵称</view>
				<view class="avatar-section">
					<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
						<image 
							class="avatar"
							:src="tempUserInfo.avatarUrl ? 
								(tempUserInfo.avatarUrl.startsWith('http') ? tempUserInfo.avatarUrl : $baseUrl + tempUserInfo.avatarUrl) : 
								(userInfo.avatar ? ($baseUrl + userInfo.avatar) : '/static/avatar/default.png')"
						></image>
					</button>
					<text class="tip">点击修改头像</text>
				</view>
				<view class="nickname-section">
					<text class="label">昵称</text>
					<input type="nickname" class="nickname-input" placeholder="请输入昵称" :value="tempUserInfo.nickName"
						@input="onNicknameChange" />
				</view>
				<view class="btn-group">
					<text class="btn cancel" @tap="closeEditPopup">取消</text>
					<text class="btn confirm" @tap="confirmEdit">确定</text>
				</view>
			</view>
		</view>

		<!-- 手机号授权弹框 -->
		<phone-auth :show="showPhoneAuth" @success="handlePhoneAuthSuccess" @fail="handlePhoneAuthCancel"
			@cancel="handlePhoneAuthCancel" />
	</view>
</template>

<script>
	import {
		userStorage
	} from '@/utils/storage'
	import {
		formatPhone
	} from '@/utils/format'
	import {
		userApi
	} from '@/api'
	import PhoneAuth from '@/components/phone-auth/index.vue'

	export default {
		components: {
			PhoneAuth
		},
		data() {
			return {
				showPhoneAuth: false,
				showEditPopup: false,
				userInfo: {},
				tempUserInfo: {
					avatarUrl: '',
					nickName: ''
				},
			}
		},
		computed: {
			isLogin() {
				return userStorage.isLogin()
			}
		},
		onShow() {
			this.getUserInfo()
			// 检查是否需要手机号授权
			if (userStorage.getNeedPhone()) {
				this.showPhoneAuth = true
			}
		},
		methods: {
			formatPhone,
			getUserInfo() {
				const userInfo = userStorage.getUserInfo()
				if (userInfo) {
					this.userInfo = userInfo
				}
			},
			handleLogin() {
				this.showPhoneAuth = true
			},
			handlePhoneAuthSuccess() {
				this.showPhoneAuth = false
				this.getUserInfo()
			},
			handlePhoneAuthCancel() {
				this.showPhoneAuth = false
			},
			// 处理服务功能点击
			handleService(type) {
				switch (type) {
					case 'room':
						uni.navigateTo({
							url: '/pages/question-list/index'
						})
						break
					case 'order':
						uni.navigateTo({
							url: '/pages/order-list/index'
						})
						break
					case 'booking':
						uni.navigateTo({
							url: '/pages/booking-list/index'
						})
						break
					case 'service':
						uni.makePhoneCall({
							phoneNumber: '18969698907'
						})
						break
				}
			},
			handleEditUserInfo() {
				// 先检查登录状态
				if (!this.isLogin) {
					this.showPhoneAuth = true
					return
				}
				
				this.showEditPopup = true
				this.tempUserInfo = {
					avatarUrl: this.userInfo.avatar ? (this.$baseUrl + this.userInfo.avatar) : '',
					nickName: this.userInfo.username || ''
				}
			},
			closeEditPopup() {
				this.showEditPopup = false
				this.tempUserInfo = {
					avatarUrl: '',
					nickName: ''
				}
			},
			onChooseAvatar(e) {
				const that = this
				// 先设置临时预览，这时是微信临时文件路径
				that.tempUserInfo.avatarUrl = e.detail.avatarUrl

				// 检查登录状态
				const token = userStorage.getToken()
				if (!token) {
					that.showPhoneAuth = true
					return
				}

				// 上传到我们的服务器
				uni.uploadFile({
					url: this.$baseUrl + "/common/upload",
					filePath: e.detail.avatarUrl,
					name: 'file',
					header: {
						"Authorization": `Bearer ${token}`
					},
					success(res) {
						try {
							const data = JSON.parse(res.data)
							if (data.code === 200) {
								// 更新为服务器返回的地址
								that.tempUserInfo.avatarUrl = that.$baseUrl + data.fileName
							} else if (data.code === 401) {
								// token 过期，需要重新登录
								userStorage.clear()
								that.showPhoneAuth = true
								// 保存临时文件路径，登录后继续上传
								that.tempUserInfo.avatarUrl = e.detail.avatarUrl
							} else {
								uni.showToast({
									title: data.msg || '上传失败',
									icon: 'none'
								})
							}
						} catch (err) {
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							})
						}
					},
					fail(err) {
						// 如果是 token 相关错误，触发登录
						if (err.statusCode === 401) {
							userStorage.clear()
							that.showPhoneAuth = true
							// 保存临时文件路径，登录后继续上传
							that.tempUserInfo.avatarUrl = e.detail.avatarUrl
						} else {
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							})
						}
					}
				})
			},
			onNicknameChange(e) {
				this.tempUserInfo.nickName = e.detail.value
			},
			confirmEdit() {
				if (!this.tempUserInfo.nickName) {
					uni.showToast({
						title: '请输入昵称',
						icon: 'none'
					})
					return
				}

				uni.showLoading({
					title: '保存中...'
				})
				
				// 处理头像路径
				const avatar = this.tempUserInfo.avatarUrl.replace(this.$baseUrl, '')
				
				userApi.updateUserInfo({
					id: this.userInfo.id,
					username: this.tempUserInfo.nickName,
					avatar: avatar // 只传递相对路径
				}).then(res => {
					// 更新本地存储
					const newUserInfo = {
						...this.userInfo,
						username: this.tempUserInfo.nickName,
						avatar: avatar // 保存相对路径
					}
					userStorage.setUserInfo(newUserInfo)
					this.userInfo = newUserInfo

					uni.hideLoading()
					uni.showToast({
						title: '保存成功',
						icon: 'success'
					})
					this.closeEditPopup()
				}).catch(err => {
					uni.hideLoading()
					uni.showToast({
						title: err.message || '保存失败',
						icon: 'none'
					})
				})
			}
		}
	}
</script>

<style lang="scss">
	.my {
		min-height: 100vh;
		background-color: #f8f8f8;
		padding-top: 20rpx;

		// 用户信息区域
		.user-info {
			margin: 0 20rpx;
			padding: 30rpx;
			padding-top: 120rpx;
			background-color: #fff;
			border-radius: 12rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.info-content {
				display: flex;
				align-items: center;
				flex: 1;
			}

			.avatar {
				width: 120rpx;
				height: 120rpx;
				border-radius: 60rpx;
			}

			.info {
				margin-left: 30rpx;
				display: flex;
				flex-direction: column;
				justify-content: center;

				.name {
					font-size: 32rpx;
					color: #333;
					font-weight: 500;
					line-height: 1.5;
				}

				.phone {
					font-size: 28rpx;
					color: #999;
					line-height: 1.5;
					margin-top: 4rpx;
				}
			}

			.login-btn {
				margin-left: 30rpx;
				padding: 0;
				width: 160rpx !important;
				height: 64rpx;
				line-height: 64rpx;
				background: linear-gradient(to right, #1989fa, #39b9fa);
				border-radius: 32rpx;
				border: none;
				text-align: center;

				text {
					color: #fff;
					font-size: 28rpx;
					font-weight: normal;
				}

				&::after {
					display: none;
				}

				&:active {
					opacity: 0.8;
				}
			}

			.edit-icon {
				padding: 20rpx;

				image {
					width: 40rpx;
					height: 40rpx;
				}

				&:active {
					opacity: 0.7;
				}
			}
		}

		// 服务功能区域
		.service-section {
			margin: 20rpx;
			padding: 30rpx;
			background-color: #fff;
			border-radius: 12rpx;

			.section-title {
				font-size: 28rpx;
				color: #333;
				font-weight: bold;
			}

			.service-list {
				margin-top: 20rpx;

				.service-item {
					display: flex;
					align-items: center;
					padding: 30rpx 0;
					border-bottom: 2rpx solid #f5f5f5;

					&:last-child {
						border-bottom: none;
					}

					.icon {
						width: 40rpx;
						height: 40rpx;
					}

					.text {
						flex: 1;
						margin-left: 20rpx;
						font-size: 28rpx;
						color: #333;
					}

					.arrow {
						font-size: 28rpx;
						color: #999;
					}
				}
			}
		}

		.edit-popup {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background: rgba(0, 0, 0, 0.5);
			z-index: 100;
			display: flex;
			align-items: center;
			justify-content: center;

			.edit-content {
				width: 600rpx;
				background: #fff;
				border-radius: 20rpx;
				padding: 40rpx;

				.title {
					font-size: 32rpx;
					color: #333;
					font-weight: 500;
					text-align: center;
					margin-bottom: 40rpx;
				}

				.avatar-section {
					display: flex;
					flex-direction: column;
					align-items: center;
					margin-bottom: 40rpx;

					.avatar-wrapper {
						padding: 0;
						width: 160rpx;
						height: 160rpx;
						background: none;

						&::after {
							border: none;
						}

						.avatar {
							width: 160rpx;
							height: 160rpx;
							border-radius: 80rpx;
						}
					}

					.tip {
						font-size: 24rpx;
						color: #999;
						margin-top: 10rpx;
					}
				}

				.nickname-section {
					display: flex;
					align-items: center;
					margin-bottom: 40rpx;

					.label {
						font-size: 28rpx;
						color: #333;
						margin-right: 20rpx;
					}

					.nickname-input {
						flex: 1;
						height: 80rpx;
						border: 2rpx solid #eee;
						border-radius: 8rpx;
						padding: 0 20rpx;
						font-size: 28rpx;
					}
				}

				.btn-group {
					display: flex;
					justify-content: space-between;

					.btn {
						width: 240rpx;
						height: 80rpx;
						line-height: 80rpx;
						text-align: center;
						border-radius: 40rpx;
						font-size: 28rpx;

						&.cancel {
							color: #666;
							border: 2rpx solid #ddd;
						}

						&.confirm {
							color: #fff;
							background: #1989fa;
						}

						&:active {
							opacity: 0.8;
						}
					}
				}
			}
		}
	}
</style>